package com.ruoyi.demo.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.demo.util.MinIOUtil;
import com.ruoyi.demo.util.MediaSyncUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/demo/minio")
public class MinioTestController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(MinioTestController.class);

    @Autowired
    private MinIOUtil minIOUtil;

    @Autowired
    private MediaSyncUtil mediaSyncUtil;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    /**
     * 测试文件上传
     */
    @PostMapping("/upload/file")
    public AjaxResult uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("meetId") String meetId) {
        try {
            // 构建存储路径
            String path = "meet/" + meetId + "/files/";
            String fileName = file.getOriginalFilename();

            // 上传文件
            String url = minIOUtil.uploadImage(file, path, fileName);
            log.info("文件上传成功，访问地址：{}", url);

            return AjaxResult.success("上传成功", url);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 获取文件列表
     */
    @GetMapping("/list/{meetId}")
    public AjaxResult getFileList(@PathVariable("meetId") String meetId) {
        try {
            String prefix = "meet/" + meetId + "/files/";
            List<String> fileList = minIOUtil.getFileList(prefix);
            return AjaxResult.success("获取文件列表成功", fileList);
        } catch (Exception e) {
            log.error("获取文件列表失败", e);
            return AjaxResult.error("获取文件列表失败：" + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/delete/{meetId}/{fileName}")
    public AjaxResult deleteFile(
            @PathVariable("meetId") String meetId,
            @PathVariable("fileName") String fileName) {
        try {
            String objectName = "meet/" + meetId + "/files/" + fileName;
            boolean result = minIOUtil.deleteFile(objectName);
            if (result) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除文件失败", e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 测试音视频同步
     */
    @PostMapping("/testSync")
    public AjaxResult testSync(@RequestParam("videoFileName") String videoFileName,
                               @RequestParam("audioFileName") String audioFileName) {
        try {
            log.info("开始测试音视频同步 - 视频：{}，音频：{}", videoFileName, audioFileName);

            // 创建临时目录用于存储同步后的文件
            String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String tempDir = uploadPath + File.separator + "temp" + File.separator + dateDir;
            File dir = new File(tempDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成同步后的文件名
            String syncedFileName = "test_synced_" + System.currentTimeMillis() + ".mp4";
            String outputPath = tempDir + File.separator + syncedFileName;

            // 执行音视频同步
            String syncedPath = mediaSyncUtil.syncMediaFiles(videoFileName, audioFileName, outputPath);
            log.info("音视频同步完成：{}", syncedPath);

            // 上传到MinIO
            String minioUrl = minIOUtil.uploadVideo(
                    new MockMultipartFile(
                            syncedFileName,
                            syncedFileName,
                            "video/mp4",
                            new FileInputStream(new File(syncedPath))
                    ),
                    "test/sync",
                    syncedFileName
            );
            log.info("同步文件上传完成：{}", minioUrl);

            // 清理临时文件
            new File(syncedPath).delete();

            return AjaxResult.success("音视频同步测试完成", minioUrl);
        } catch (Exception e) {
            log.error("音视频同步测试失败", e);
            return AjaxResult.error("音视频同步测试失败：" + e.getMessage());
        }
    }
}
